import 'package:flutter/material.dart';
import '../../models/post_model.dart';
import '../../models/post_type.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import '../../utils/cached_image_widget.dart';
import 'package:base_flutter/src/network/network_exception.dart';
import 'article_detail_page.dart';
import 'video_collection_page.dart';
import 'post_detail_page.dart';
import 'video_player_page.dart';
import 'service_detail_page.dart';

/// 热门页面 - 重构版
/// 根据动态类型显示不同的卡片样式和跳转逻辑
class HotPageV2 extends StatefulWidget {
  const HotPageV2({super.key});

  @override
  State<HotPageV2> createState() => _HotPageV2State();
}

class _HotPageV2State extends State<HotPageV2> {
  String _selectedCategory = '全部';
  String _selectedSort = '最新';
  String? _selectedPostType;

  List<String> _categories = ['全部'];
  List<Map<String, dynamic>> _categoryData = []; // 存储完整的分类数据
  final List<String> _sortOptions = ['最新', '最热', '附近'];
  final List<String> _postTypes = ['全部', '图文', '文章', '视频', '商品'];

  // 数据状态
  List<PostModel> _posts = [];
  bool _isLoading = false;
  bool _hasMore = true;
  int _currentPage = 1;
  final int _pageSize = 20;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    _loadCategories();
    _loadPosts();
    
    // 打印缓存统计信息
    Logger.d('🚀 HOT_PAGE_INIT', '==================== 热门页面初始化 ====================');
    Logger.d('🚀 HOT_PAGE_INIT', '页面启动，开始加载数据...');
    Logger.d('🚀 HOT_PAGE_INIT', '图片缓存: 使用 cached_network_image 本地缓存');
    Logger.d('🚀 HOT_PAGE_INIT', '数据缓存: 使用 SharedPreferences 本地缓存 (2小时有效)');
    Logger.d('🚀 HOT_PAGE_INIT', '=======================================================');
  }

  @override
  void dispose() {
    _scrollController.dispose();
    // 页面销毁时打印缓存统计
    Logger.d('📊 HOT_PAGE_DISPOSE', '==================== 热门页面销毁 ====================');
    AppCacheManager.printCacheStats();
    Logger.d('📊 HOT_PAGE_DISPOSE', '=======================================================');
    super.dispose();
  }

  /// 滚动监听，实现上拉加载更多
  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      if (!_isLoading && _hasMore) {
        _loadMorePosts();
      }
    }
  }

  /// 加载热门动态列表
  ///
  /// ⚠️ 当前使用旧版算法（简单排序）
  /// TODO: 迁移到新的智能推荐算法 ApiService().getRecommendedPosts()
  ///
  /// 新算法优势：
  /// - 60% 基于用户兴趣标签推荐
  /// - 20% 系统热门内容
  /// - 20% 探索性内容发现新兴趣
  ///
  /// 保留旧算法原因：向后兼容、A/B测试、降级备用
  Future<void> _loadPosts({bool refresh = false}) async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
      if (refresh) {
        _currentPage = 1;
        _hasMore = true;
        _posts.clear();
      }
    });

    try {
      final sortMap = {'最新': 'latest', '最热': 'hot', '附近': 'nearby'};
      final postTypeMap = {
        '图文': 'text',
        '文章': 'article',
        '视频': 'video',
        '商品': 'service'
      };

      // ⚠️ 旧版API调用 - 建议迁移到 getRecommendedPosts()
      // ignore: deprecated_member_use
      final newPosts = await ApiService().getHotPosts(
        page: _currentPage,
        pageSize: _pageSize,
        category: _selectedCategory == '全部' ? null : _selectedCategory,
        sort: sortMap[_selectedSort] ?? 'latest',
        postType:
            _selectedPostType == '全部' ? null : postTypeMap[_selectedPostType],
        forceRefresh: refresh,
      );

      setState(() {
        if (refresh) {
          _posts = newPosts;
        } else {
          _posts.addAll(newPosts);
        }
        _hasMore = newPosts.length >= _pageSize;
        _currentPage++;
      });

      Logger.d('HOT_PAGE_V2', '加载动态成功，当前数量: ${_posts.length}');

      // 🔍 调试日志：输出每个帖子的详细数据
      for (var i = 0; i < newPosts.length; i++) {
        final post = newPosts[i];
        Logger.d('HOT_PAGE_V2_DEBUG', '========== 帖子 #$i 数据 ==========');
        Logger.d('HOT_PAGE_V2_DEBUG', 'ID: ${post.id}');
        Logger.d('HOT_PAGE_V2_DEBUG', '用户: ${post.username}');
        Logger.d('HOT_PAGE_V2_DEBUG', '类型: ${post.postType}');
        Logger.d('HOT_PAGE_V2_DEBUG', '标题: ${post.title}');
        Logger.d('HOT_PAGE_V2_DEBUG', '封面图URL: ${post.coverUrl}');
        Logger.d('HOT_PAGE_V2_DEBUG', '图片列表数量: ${post.images.length}');
        if (post.images.isNotEmpty) {
          for (var j = 0; j < post.images.length; j++) {
            Logger.d('HOT_PAGE_V2_DEBUG', '  图片[$j]: ${post.images[j]}');
          }
        }
        Logger.d('HOT_PAGE_V2_DEBUG', '用户头像: ${post.userAvatar}');
        Logger.d('HOT_PAGE_V2_DEBUG',
            '点赞数: ${post.likesCount}, 评论数: ${post.commentsCount}');
        Logger.d('HOT_PAGE_V2_DEBUG', '====================================');
      }
    } catch (e) {
      Logger.e('HOT_PAGE_V2', '加载动态失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content:
                Text('加载失败: ${e is NetworkException ? e.message : '网络错误'}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  /// 加载更多动态
  Future<void> _loadMorePosts() async {
    await _loadPosts();
  }

  /// 刷新数据
  Future<void> _refreshPosts() async {
    await _loadPosts(refresh: true);
  }

  /// 加载分类列表
  Future<void> _loadCategories() async {
    try {
      final categoriesData = await ApiService().getContentCategories();
      setState(() {
        _categoryData = List<Map<String, dynamic>>.from(categoriesData);
        _categories = ['全部'] +
            categoriesData
                .map((category) => category['name'] as String)
                .toList();
      });
      Logger.d('HotPageV2', '成功加载分类: ${_categories.length}个');
    } catch (e) {
      Logger.e('HotPageV2', '加载分类失败: $e');
      // 使用默认分类作为后备方案
      setState(() {
        _categoryData = [
          {'id': '1', 'name': '科技', 'color': '#1890ff'},
          {'id': '2', 'name': '文娱', 'color': '#52c41a'},
          {'id': '3', 'name': '游戏', 'color': '#fa8c16'},
          {'id': '4', 'name': '旅行', 'color': '#13c2c2'},
          {'id': '5', 'name': '美食', 'color': '#eb2f96'},
          {'id': '6', 'name': '运动', 'color': '#722ed1'},
          {'id': '7', 'name': '教育', 'color': '#fa541c'},
          {'id': '8', 'name': '其他', 'color': '#8c8c8c'},
        ];
        _categories = ['全部', '科技', '文娱', '游戏', '旅行', '美食', '运动', '教育', '其他'];
      });
    }
  }

  /// 获取分类信息
  Map<String, dynamic> _getCategoryInfo(String categoryName) {
    if (categoryName == '全部') {
      return {'id': '0', 'name': '全部', 'color': null};
    }

    final category = _categoryData.firstWhere(
      (cat) => cat['name'] == categoryName,
      orElse: () => {'id': '0', 'name': categoryName, 'color': null},
    );

    return category;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // 顶部标题栏
          Container(
            padding: const EdgeInsets.only(top: 48, bottom: 12),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.1),
                  spreadRadius: 1,
                  blurRadius: 2,
                  offset: const Offset(0, 1),
                ),
              ],
            ),
            child: Row(
              children: [
                // 标题
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(left: 16),
                    child: Text(
                      '热门内容',
                      style: TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 筛选区域
          Container(
            padding: const EdgeInsets.symmetric(vertical: 6),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                bottom: BorderSide(
                  color: Colors.grey.withOpacity(0.1),
                  width: 1,
                ),
              ),
            ),
            child: Column(
              children: [
                // 分类筛选
                SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    children: _categories.map((category) {
                      final isSelected = _selectedCategory == category;
                      final categoryInfo = _getCategoryInfo(category);

                      return Padding(
                        padding: const EdgeInsets.only(right: 8),
                        child: FilterChip(
                          label: Text(
                            category,
                            style: TextStyle(
                              color: isSelected
                                  ? Colors.white
                                  : (categoryInfo['color'] != null
                                      ? Color(int.parse(categoryInfo['color']!
                                          .replaceFirst('#', '0xff')))
                                      : Colors.grey[600]),
                              fontWeight: isSelected
                                  ? FontWeight.w600
                                  : FontWeight.normal,
                            ),
                          ),
                          selected: isSelected,
                          backgroundColor: categoryInfo['color'] != null
                              ? Color(int.parse(categoryInfo['color']!
                                      .replaceFirst('#', '0xff')))
                                  .withOpacity(0.1)
                              : Colors.grey[100],
                          selectedColor: categoryInfo['color'] != null
                              ? Color(int.parse(categoryInfo['color']!
                                  .replaceFirst('#', '0xff')))
                              : Theme.of(context).primaryColor,
                          checkmarkColor: Colors.white,
                          onSelected: (selected) {
                            setState(() {
                              _selectedCategory = category;
                            });
                            _refreshPosts();
                          },
                        ),
                      );
                    }).toList(),
                  ),
                ),
                const SizedBox(height: 8),
                // 动态类型筛选
                SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    children: _postTypes.map((postType) {
                      return Padding(
                        padding: const EdgeInsets.only(right: 8),
                        child: FilterChip(
                          label: Text(postType),
                          selected: _selectedPostType == postType,
                          onSelected: (selected) {
                            setState(() {
                              _selectedPostType = postType;
                            });
                            _refreshPosts();
                          },
                        ),
                      );
                    }).toList(),
                  ),
                ),
                const SizedBox(height: 8),
                // 排序选项
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: _sortOptions.map((sort) {
                    return Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 8),
                      child: _buildMenuButton(sort, _sortOptions.indexOf(sort)),
                    );
                  }).toList(),
                ),
              ],
            ),
          ),

          // 动态列表
          Expanded(
            child: RefreshIndicator(
              onRefresh: _refreshPosts,
              child: ListView.builder(
                controller: _scrollController,
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                itemCount: _posts.length + (_isLoading ? 1 : 0),
                itemBuilder: (context, index) {
                  if (index == _posts.length) {
                    return _buildLoadingIndicator();
                  }
                  final post = _posts[index];
                  return Padding(
                    padding: const EdgeInsets.only(bottom: 12),
                    child: _buildPostCard(post),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMenuButton(String title, int index) {
    final isSelected = _selectedSort == title;
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedSort = title;
        });
        _refreshPosts();
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color:
              isSelected ? Theme.of(context).primaryColor : Colors.transparent,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color:
                isSelected ? Theme.of(context).primaryColor : Colors.grey[300]!,
          ),
        ),
        child: Text(
          title,
          style: TextStyle(
            fontSize: 14,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
            color: isSelected ? Colors.white : Colors.grey[600],
          ),
        ),
      ),
    );
  }

  /// 构建加载指示器
  Widget _buildLoadingIndicator() {
    return Container(
      padding: const EdgeInsets.all(16),
      alignment: Alignment.center,
      child: _isLoading
          ? const CircularProgressIndicator()
          : _hasMore
              ? const SizedBox.shrink()
              : const Text(
                  '没有更多内容了',
                  style: TextStyle(color: Colors.grey),
                ),
    );
  }

  /// 构建动态卡片 - 根据类型显示不同样式
  Widget _buildPostCard(PostModel post) {
    // 🔍 调试日志：构建卡片时输出数据
    Logger.d('HOT_PAGE_V2_RENDER',
        '渲染卡片 - ID: ${post.id}, 类型: ${post.postType}, 封面: ${post.coverUrl}, 图片数: ${post.images.length}');

    switch (post.postType) {
      case PostType.text:
        return _buildTextPostCard(post); // 图文类型（兼容旧数据）
      case PostType.article:
        return _buildArticlePostCard(post);
      case PostType.video:
      case PostType.videoCollection:
        return _buildVideoPostCard(post); // 视频和视频集都用视频卡片
      case PostType.service:
        return _buildServicePostCard(post);
    }
  }

  /// 图文动态卡片
  Widget _buildTextPostCard(PostModel post) {
    Logger.d('HOT_PAGE_V2_RENDER',
        '构建图文卡片 - ID: ${post.id}, 封面URL: ${post.coverUrl}');

    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () => _handlePostTap(post),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildUserInfo(post),
              const SizedBox(height: 10),
              // 封面图片（如果有）- 使用缓存组件加速加载
              if (post.coverUrl != null) ...[
                CachedImageWidget(
                  imageUrl: post.coverUrl,
                  width: double.infinity,
                  height: 180,
                  fit: BoxFit.cover,
                  borderRadius: BorderRadius.circular(8),
                  imageType: '图文封面',
                ),
                const SizedBox(height: 10),
              ],
              // 只显示标题，不显示正文内容
              Text(
                _cleanHtmlContent(post.title ?? '无标题'),
                style:
                    const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 10),
              _buildActionButtons(post),
            ],
          ),
        ),
      ),
    );
  }

  /// 图片动态卡片
  Widget _buildImagePostCard(PostModel post) {
    Logger.d(
        'HOT_PAGE_V2_RENDER', '构建图片卡片 - ID: ${post.id}, 图片列表: ${post.images}');

    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () => _handlePostTap(post),
        borderRadius: BorderRadius.circular(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息
            Padding(
              padding: const EdgeInsets.all(12),
              child: _buildUserInfo(post),
            ),
            // 图片网格
            if (post.images.isNotEmpty) ...[
              _buildImageGrid(post.images),
              const SizedBox(height: 10),
            ],
            // 只显示标题，不显示正文内容
            if (post.title?.isNotEmpty ?? false) ...[
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 12),
                child: Text(
                  _cleanHtmlContent(post.title!),
                  style: const TextStyle(
                      fontSize: 16, fontWeight: FontWeight.w500),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              const SizedBox(height: 10),
            ],
            // 互动按钮
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child: _buildActionButtons(post),
            ),
            const SizedBox(height: 12),
          ],
        ),
      ),
    );
  }

  /// 文章动态卡片
  Widget _buildArticlePostCard(PostModel post) {
    Logger.d('HOT_PAGE_V2_RENDER',
        '构建文章卡片 - ID: ${post.id}, 封面URL: ${post.coverUrl}');

    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () => _handlePostTap(post),
        borderRadius: BorderRadius.circular(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息
            Padding(
              padding: const EdgeInsets.all(12),
              child: _buildUserInfo(post),
            ),
            // 文章封面 - 使用缓存组件加速加载
            if (post.coverUrl != null) ...[
              CachedImageWidget(
                imageUrl: post.coverUrl,
                width: double.infinity,
                height: 200,
                fit: BoxFit.cover,
                borderRadius: const BorderRadius.only(
                  bottomLeft: Radius.circular(12),
                  bottomRight: Radius.circular(12),
                ),
                imageType: '文章封面',
                errorWidget: Container(
                  height: 200,
                  color: Colors.grey[200],
                  child: const Icon(Icons.article, size: 50),
                ),
              ),
            ],
            // 文章信息
            Padding(
              padding: const EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _cleanHtmlContent(post.title ?? '无标题'),
                    style: const TextStyle(
                        fontSize: 18, fontWeight: FontWeight.bold),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  if (post.summary != null && post.summary!.isNotEmpty) ...[
                    const SizedBox(height: 8),
                    Text(
                      _cleanHtmlContent(post.summary!),
                      style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                  const SizedBox(height: 10),
                  _buildActionButtons(post),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 视频动态卡片
  Widget _buildVideoPostCard(PostModel post) {
    Logger.d('HOT_PAGE_V2_RENDER',
        '构建视频卡片 - ID: ${post.id}, 封面URL: ${post.coverUrl}, 视频URL: ${post.videoUrl}');

    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () => _handlePostTap(post),
        borderRadius: BorderRadius.circular(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息
            Padding(
              padding: const EdgeInsets.all(12),
              child: _buildUserInfo(post),
            ),
            // 视频封面区域 - 优化显示，确保完整显示
            Container(
              width: double.infinity,
              constraints: const BoxConstraints(
                minHeight: 200,
                maxHeight: 400,
              ),
              child: Stack(
                children: [
                  ClipRRect(
                    borderRadius: const BorderRadius.only(
                      bottomLeft: Radius.circular(12),
                      bottomRight: Radius.circular(12),
                    ),
                    // 视频封面 - 使用缓存组件加速加载
                    child: post.coverUrl != null && post.coverUrl!.isNotEmpty
                        ? AspectRatio(
                            aspectRatio: 16 / 9, // 标准视频比例
                            child: CachedImageWidget(
                              imageUrl: post.coverUrl,
                              width: double.infinity,
                              fit: BoxFit.cover,
                              borderRadius: BorderRadius.zero,
                              imageType: '视频封面',
                              errorWidget: _buildVideoPlaceholder(),
                            ),
                          )
                        : _buildVideoPlaceholder(),
                  ),
                  // 播放按钮 - 始终显示在中心
                  Positioned.fill(
                    child: Center(
                      child: Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.6),
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.play_arrow,
                          color: Colors.white,
                          size: 50,
                        ),
                      ),
                    ),
                  ),
                  // 视频时长标签（如果有）
                  if (post.videoUrl != null && post.videoUrl!.isNotEmpty)
                    Positioned(
                      bottom: 12,
                      right: 12,
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.7),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: const Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.play_circle_outline,
                              color: Colors.white,
                              size: 14,
                            ),
                            SizedBox(width: 4),
                            Text(
                              '视频',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 12,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                ],
              ),
            ),
            // 视频信息
            Padding(
              padding: const EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _cleanHtmlContent(post.title ?? post.content),
                    style: const TextStyle(
                        fontSize: 16, fontWeight: FontWeight.w500),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 10),
                  _buildActionButtons(post),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建视频占位图
  Widget _buildVideoPlaceholder() {
    return AspectRatio(
      aspectRatio: 16 / 9, // 标准视频比例
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Colors.grey[300]!,
              Colors.grey[400]!,
            ],
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.videocam,
              size: 60,
              color: Colors.grey[600],
            ),
            const SizedBox(height: 8),
            Text(
              '视频',
              style: TextStyle(
                color: Colors.grey[600],
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 商品动态卡片
  Widget _buildServicePostCard(PostModel post) {
    Logger.d('HOT_PAGE_V2_RENDER',
        '构建商品卡片 - ID: ${post.id}, 封面URL: ${post.coverUrl}');

    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () => _handlePostTap(post),
        borderRadius: BorderRadius.circular(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息
            Padding(
              padding: const EdgeInsets.all(12),
              child: _buildUserInfo(post),
            ),
            // 商品图片 - 使用缓存组件加速加载
            if (post.coverUrl != null) ...[
              CachedImageWidget(
                imageUrl: post.coverUrl,
                width: double.infinity,
                height: 200,
                fit: BoxFit.cover,
                borderRadius: const BorderRadius.only(
                  bottomLeft: Radius.circular(12),
                  bottomRight: Radius.circular(12),
                ),
                imageType: '商品封面',
                errorWidget: Container(
                  height: 200,
                  color: Colors.grey[200],
                  child: const Icon(Icons.shopping_bag, size: 50),
                ),
              ),
            ],
            // 商品信息
            Padding(
              padding: const EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _cleanHtmlContent(post.title ?? post.content),
                    style: const TextStyle(
                        fontSize: 16, fontWeight: FontWeight.w500),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 8),
                  // 价格标签（如果有）
                  Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.red.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.red.withOpacity(0.3)),
                    ),
                    child: Text(
                      '商品',
                      style: TextStyle(
                        color: Colors.red,
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                  const SizedBox(height: 10),
                  _buildActionButtons(post),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建用户信息
  Widget _buildUserInfo(PostModel post) {
    return Row(
      children: [
        // 用户头像 - 使用缓存组件加速加载
        CachedAvatarWidget(
          avatarUrl: post.userAvatar,
          size: 40,
        ),
        const SizedBox(width: 10),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    post.username,
                    style: const TextStyle(
                        fontWeight: FontWeight.bold, fontSize: 16),
                  ),
                  if (post.isHot) ...[
                    const SizedBox(width: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: const Text(
                        '热门',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 10,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                  ],
                  const SizedBox(width: 8),
                  _buildPostTypeTag(post.postType),
                ],
              ),
              Row(
                children: [
                  Icon(Icons.location_on, size: 12, color: Colors.grey[600]),
                  const SizedBox(width: 4),
                  Text(
                    post.location ?? '',
                    style: TextStyle(color: Colors.grey[600], fontSize: 12),
                  ),
                  const SizedBox(width: 8),
                  Text(
                    _getTimeAgo(post.createdAt),
                    style: TextStyle(color: Colors.grey[600], fontSize: 12),
                  ),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建动态类型标签
  Widget _buildPostTypeTag(PostType postType) {
    String text;
    Color color;

    switch (postType) {
      case PostType.text:
        text = '图文';
        color = Colors.blue;
        break;
      case PostType.article:
        text = '文章';
        color = Colors.orange;
        break;
      case PostType.video:
        text = '视频';
        color = Colors.purple;
        break;
      case PostType.videoCollection:
        text = '视频集';
        color = Colors.indigo;
        break;
      case PostType.service:
        text = '商品';
        color = Colors.red;
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Text(
        text,
        style:
            TextStyle(color: color, fontSize: 10, fontWeight: FontWeight.w500),
      ),
    );
  }

  /// 构建图片网格 - 使用缓存组件加速加载
  Widget _buildImageGrid(List<String> images) {
    Logger.d('HOT_PAGE_V2_IMAGE', '构建图片网格 - 图片数量: ${images.length}');

    if (images.length == 1) {
      return CachedImageWidget(
        imageUrl: images[0],
        width: double.infinity,
        height: 200,
        fit: BoxFit.cover,
        borderRadius: BorderRadius.circular(8),
        imageType: '动态图片',
      );
    } else if (images.length == 2) {
      return Row(
        children: [
          Expanded(
            child: CachedImageWidget(
              imageUrl: images[0],
              height: 150,
              fit: BoxFit.cover,
              borderRadius: BorderRadius.circular(8),
              imageType: '动态图片',
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: CachedImageWidget(
              imageUrl: images[1],
              height: 150,
              fit: BoxFit.cover,
              borderRadius: BorderRadius.circular(8),
              imageType: '动态图片',
            ),
          ),
        ],
      );
    } else {
      return GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 8,
          mainAxisSpacing: 8,
        ),
        itemCount: images.length > 9 ? 9 : images.length,
        itemBuilder: (context, index) {
          return ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Stack(
              fit: StackFit.expand,
              children: [
                CachedImageWidget(
                  imageUrl: images[index],
                  fit: BoxFit.cover,
                  borderRadius: BorderRadius.zero,
                  imageType: '动态图片',
                ),
                if (index == 8 && images.length > 9)
                  Container(
                    color: Colors.black.withOpacity(0.5),
                    child: Center(
                      child: Text(
                        '+${images.length - 9}',
                        style: const TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
              ],
            ),
          );
        },
      );
    }
  }

  /// 构建互动按钮
  Widget _buildActionButtons(PostModel post) {
    return Row(
      children: [
        _buildActionButton(
          icon: post.isLiked ? Icons.favorite : Icons.favorite_border,
          label: '${post.likesCount}',
          color: post.isLiked ? Colors.red : null,
          onTap: () => _handleLike(post),
        ),
        const SizedBox(width: 24),
        _buildActionButton(
          icon: Icons.share,
          label: '${post.sharesCount}',
          onTap: () => _handleShare(post),
        ),
        const SizedBox(width: 24),
        _buildActionButton(
          icon: Icons.visibility,
          label: '${post.viewsCount}',
          onTap: () {},
        ),
      ],
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required String label,
    Color? color,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Row(
        children: [
          Icon(icon, size: 20, color: color ?? Colors.grey[600]),
          const SizedBox(width: 4),
          Text(label,
              style: TextStyle(color: color ?? Colors.grey[600], fontSize: 14)),
        ],
      ),
    );
  }

  String _getTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  /// 清理HTML内容，移除HTML标签和实体
  String _cleanHtmlContent(String content) {
    if (content.isEmpty) return content;

    // 移除HTML标签
    String cleaned = content.replaceAll(RegExp(r'<[^>]*>'), '');

    // 替换HTML实体
    cleaned = cleaned
        .replaceAll('&nbsp;', ' ')
        .replaceAll('&lt;', '<')
        .replaceAll('&gt;', '>')
        .replaceAll('&amp;', '&')
        .replaceAll('&quot;', '"')
        .replaceAll('&#39;', "'")
        .replaceAll('&apos;', "'")
        .replaceAll('&hellip;', '...')
        .replaceAll('&mdash;', '—')
        .replaceAll('&ndash;', '–')
        .replaceAll('&copy;', '©')
        .replaceAll('&reg;', '®')
        .replaceAll('&trade;', '™');

    // 清理多余的空白字符
    cleaned = cleaned.replaceAll(RegExp(r'\s+'), ' ').trim();

    return cleaned;
  }

  /// 处理动态点击
  void _handlePostTap(PostModel post) async {
    try {
      // 增加浏览量
      await ApiService().viewPost(post.id);

      // 根据动态类型跳转到不同页面
      switch (post.postType) {
        case PostType.text:
          _navigateToPostDetail(post);
        case PostType.article:
          _navigateToArticleDetail(post);
        case PostType.video:
        case PostType.videoCollection:
          _navigateToVideoPlayer(post);
        case PostType.service:
          _navigateToProductDetail(post);
      }
    } catch (e) {
      Logger.e('HOT_PAGE_V2', '处理动态点击失败: $e');
      // 即使浏览量增加失败，也继续跳转
      _handlePostTapFallback(post);
    }
  }

  /// 动态点击处理的后备方案
  void _handlePostTapFallback(PostModel post) {
    switch (post.postType) {
      case PostType.text:
        _navigateToPostDetail(post);
      case PostType.article:
        _navigateToArticleDetail(post);
      case PostType.video:
      case PostType.videoCollection:
        _navigateToVideoPlayer(post);
      case PostType.service:
        _navigateToProductDetail(post);
    }
  }

  /// 跳转到动态详情页
  void _navigateToPostDetail(PostModel post) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => PostDetailPage(post: post)),
    );
  }

  /// 跳转到文章详情页
  void _navigateToArticleDetail(PostModel post) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => ArticleDetailPage(post: post)),
    );
  }

  /// 跳转到视频播放页
  void _navigateToVideoPlayer(PostModel post) {
    Logger.d('HOT_PAGE_V2_VIDEO',
        '准备播放视频 - ID: ${post.id}, videoUrl: ${post.videoUrl}, images: ${post.images}');

    // 优先使用videoUrl，如果没有则尝试从images获取（兼容旧数据）
    String? videoUrl = post.videoUrl;

    // 如果videoUrl为空，尝试从images获取（兼容旧数据格式）
    if (videoUrl == null || videoUrl.isEmpty) {
      if (post.images.isNotEmpty) {
        videoUrl = post.images.first;
        Logger.d('HOT_PAGE_V2_VIDEO', '从images获取视频URL: $videoUrl');
      }
    }

    // 如果仍然没有视频URL，尝试从后端获取视频列表
    if (videoUrl == null || videoUrl.isEmpty) {
      Logger.w('HOT_PAGE_V2_VIDEO', '视频URL为空，尝试从后端获取视频列表');
      _loadVideoAndPlay(post);
      return;
    }

    Logger.d('HOT_PAGE_V2_VIDEO', '跳转到视频播放页 - videoUrl: $videoUrl');
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => VideoPlayerPage(
          post: post,
          videoUrl: videoUrl!,
          videoTitle: post.title ?? post.content,
        ),
      ),
    );
  }

  /// 从后端加载视频并播放
  Future<void> _loadVideoAndPlay(PostModel post) async {
    try {
      Logger.d('HOT_PAGE_V2_VIDEO', '开始从后端加载视频 - postId: ${post.id}');

      // 如果是视频合集类型，跳转到视频合集页面
      if (post.postType == PostType.videoCollection) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => VideoCollectionPage(post: post),
          ),
        );
        return;
      }

      // 如果是单个视频类型，先获取视频合集详情，然后获取视频列表
      if (post.postType == PostType.video) {
        // 1. 获取视频合集详情（包含collectionId）
        final collection = await ApiService().getVideoCollectionDetail(post.id);
        Logger.d(
            'HOT_PAGE_V2_VIDEO', '获取到视频合集 - collectionId: ${collection.id}');

        // 2. 获取视频列表
        final videos =
            await ApiService().getVideoList(collection.id.toString());
        Logger.d('HOT_PAGE_V2_VIDEO', '获取到视频列表 - 数量: ${videos.length}');

        if (videos.isEmpty) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('视频列表为空，无法播放'),
                backgroundColor: Colors.orange,
              ),
            );
          }
          return;
        }

        // 3. 取第一个视频进行播放
        final firstVideo = videos.first;
        Logger.d('HOT_PAGE_V2_VIDEO', '准备播放视频 - videoUrl: ${firstVideo.url}');

        // 确定视频标题
        final videoTitle = firstVideo.title.isNotEmpty
            ? firstVideo.title
            : (post.title?.isNotEmpty == true ? post.title! : post.content);

        if (mounted) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => VideoPlayerPage(
                post: post,
                videoUrl: firstVideo.url,
                videoTitle: videoTitle,
              ),
            ),
          );
        }
        return;
      }

      // 其他类型，显示错误提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('视频信息不完整，无法播放'),
            backgroundColor: Colors.orange,
          ),
        );
      }
    } catch (e) {
      Logger.e('HOT_PAGE_V2_VIDEO', '加载视频失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content:
                Text('加载视频失败: ${e is NetworkException ? e.message : '网络错误'}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 跳转到商品详情页
  void _navigateToProductDetail(PostModel post) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => ServiceDetailPage(post: post)),
    );
  }

  // 点赞功能
  void _handleLike(PostModel post) async {
    try {
      // 先更新UI
      setState(() {
        final index = _posts.indexWhere((p) => p.id == post.id);
        if (index != -1) {
          final newLikesCount =
              post.isLiked ? post.likesCount - 1 : post.likesCount + 1;
          _posts[index] = post.copyWith(
            isLiked: !post.isLiked,
            likesCount: newLikesCount,
          );
        }
      });

      // 调用API
      await ApiService().likePost(post.id, !post.isLiked);

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(!post.isLiked ? '已点赞' : '已取消点赞'),
          duration: const Duration(seconds: 1),
        ),
      );
    } catch (e) {
      Logger.e('HOT_PAGE_V2', '点赞操作失败: $e');
      // 回滚UI状态
      setState(() {
        final index = _posts.indexWhere((p) => p.id == post.id);
        if (index != -1) {
          _posts[index] = post;
        }
      });

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('操作失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  // 分享功能
  void _handleShare(PostModel post) async {
    try {
      // 先更新UI
      setState(() {
        final index = _posts.indexWhere((p) => p.id == post.id);
        if (index != -1) {
          _posts[index] = post.copyWith(
            sharesCount: post.sharesCount + 1,
          );
        }
      });

      // 调用API
      await ApiService().sharePost(post.id);

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('分享成功')),
      );
    } catch (e) {
      Logger.e('HOT_PAGE_V2', '分享操作失败: $e');
      // 回滚UI状态
      setState(() {
        final index = _posts.indexWhere((p) => p.id == post.id);
        if (index != -1) {
          _posts[index] = post;
        }
      });

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('分享失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
}
